﻿using Newtonsoft.Json;
using NLog;
using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LogsClearWinService.Job
{
    public class LogsClearJob : IJob
    {
        public static Logger Loger = LogManager.GetLogger("LogsClearLog");
        private static int _inTimer = 0;

        public Task Execute(IJobExecutionContext context)
        {
            if (Interlocked.Exchange(ref _inTimer, 1) == 0)
            {
                try
                {
                    Loger.Info("================LogsClear开始执行================");

                    string configPath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "\\Config\\Config.json");

                    if (!File.Exists(configPath))
                    {
                        Loger.Error("未找到Config.json文件");
                        return Task.CompletedTask;
                    }

                    string jsonContent = ReadFile(configPath);

                    if (string.IsNullOrEmpty(jsonContent))
                    {
                        Loger.Error("未找到Config.json内容是空的");
                        return Task.CompletedTask; ;
                    }

                    //反序列化对象
                    List<FileConfig> reportTypeMetadatas = JsonConvert.DeserializeObject<List<FileConfig>>(jsonContent);

                    if (reportTypeMetadatas == null || reportTypeMetadatas.Count == 0)
                        return Task.CompletedTask;

                    reportTypeMetadatas.ForEach(p =>
                    {
                        try
                        {
                            //目录不存在
                            if (!Directory.Exists(p.DirectoryPath))
                                return;

                            //获取目录下文件
                            List<FileInfo> fileList = Directory.GetFiles(p.DirectoryPath).Select(z => new FileInfo(z)).ToList();

                            if (fileList.Count > 0)
                            {
                                fileList.ForEach(a =>
                                {
                                    try
                                    {
                                        if (!File.Exists(a.FullName))
                                            return;

                                        DateTime expiresFile = DateTime.Now.AddDays(-p.FileKeepAliveDay);

                                        if (a.CreationTime < expiresFile)
                                        {
                                            File.Delete(a.FullName);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Loger.Error(ex.Message + Environment.NewLine + ex.StackTrace);
                                    }
                                });
                            }

                            //获取目录下的文件夹
                            GetDirectory(p.DirectoryPath, p.FileKeepAliveDay);
                        }
                        catch (Exception ex)
                        {
                            Loger.Error(ex.Message + Environment.NewLine + ex.StackTrace);
                        }
                        finally
                        {
                            Loger.Info("目录:" + p.DirectoryPath + "下的日志已清除");
                        }
                    });
                }
                catch (Exception ex)
                {
                    Loger.Error("清除日志发生异常，错误明细:" + ex.Message + Environment.NewLine + ex.StackTrace);
                }
                finally
                {
                    Interlocked.Exchange(ref _inTimer, 0);
                    Loger.Info("================LogsClear执行结束================");
                }
            }
            else
            {
                Loger.Info("LogsClear的上一个任务未执行完，本次任务不执行");
            }

            return Task.CompletedTask;
        }

        public static void GetDirectory(string parentDirectoryPath, int fileKeepAliveDay)
        {
            try
            {
                List<string> directoryList = Directory.GetDirectories(parentDirectoryPath).ToList();

                if (directoryList.Count > 0)
                {
                    directoryList.ForEach(p =>
                    {
                        try
                        {
                            //获取目录下文件
                            List<FileInfo> fileList = Directory.GetFiles(p).Select(z => new FileInfo(z)).ToList();

                            if (fileList.Count > 0)
                            {
                                fileList.ForEach(a =>
                                {
                                    try
                                    {
                                        if (!File.Exists(a.FullName))
                                            return;

                                        DateTime expiresFile = DateTime.Now.AddDays(-fileKeepAliveDay);

                                        if (a.CreationTime < expiresFile)
                                        {
                                            File.Delete(a.FullName);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Loger.Error(ex.Message + Environment.NewLine + ex.StackTrace);
                                    }
                                });
                            }

                            //获取目录
                            GetDirectory(p, fileKeepAliveDay);
                        }
                        catch (Exception ex)
                        {
                            Loger.Error(ex.Message + Environment.NewLine + ex.StackTrace);
                        }
                    });
                }
                else
                {
                   int fileCount=Directory.GetFiles(parentDirectoryPath).Count();

                    if(fileCount==0)
                    {
                        Directory.Delete(parentDirectoryPath);
                    }
                }
            }
            catch (Exception ex)
            {
                Loger.Error(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }

        public static string ReadFile(string Path)
        {
            string s = "";
            if (!System.IO.File.Exists(Path))
                s = "不存在相应的目录";
            else
            {
                using (StreamReader f2 = new StreamReader(Path, Encoding.GetEncoding("gb2312")))
                {
                    s = f2.ReadToEnd();
                    f2.Close();
                    f2.Dispose();
                }
            }

            return s;
        }
    }
}
